<script setup>
import { kaptchaService, userLoginService, userRegisterService } from "@/api/login";
import { useUserStore } from "@/stores/counter";
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import placeholderImage from '@/assets/svg/error.svg';

// 是否注册
const isRegister = ref(false)
// 表单对象
const formModel = ref({
    username: '',
    password: '',
    repassword: '',
    kaptcha: '',
    kaptchaUuid:''
})

// userStore
const userStore = useUserStore()
// router
const router = useRouter()

// 表单绑定对象
const loginForm = ref()
const registerForm = ref()
const captchaUrl = ref('')

// 切换登录注册
const container = ref(null)

// 规则
const rules = {
    username: [
        {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
        }
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
        },
        {
            pattern: /^\S{6,15}$/,
            message: '密码必须是6-15位的非空字符',
            trigger: 'blur'
        }
    ],
    repassword: [
        {
            required: true,
            message: '请再次输入密码',
            trigger: 'blur'
        },
        {
            pattern: /^\S{6,15}$/,
            message: '密码必须是6-15的非空字符',
            trigger: 'blur'
        },
        {
            validator: (rule, value, callback) => {
                if (value !== formModel.value.password) {
                    callback(new Error('两次输入密码不一致!'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    kaptcha: [
        {
            required: true,
            message: '请输入验证码',
            trigger: 'blur'
        }
    ]
}

/**
 * 切换注册和登录
 */
const change = () => {
    // 确保 container 有值
    if (container.value) {
        // 判断并切换 "right-panel-active" 类
        if (container.value.classList.contains('right-panel-active')) {
            container.value.classList.remove('right-panel-active'); // 移除类
        } else {
            container.value.classList.add('right-panel-active'); // 添加类
        }

        isRegister.value = !isRegister.value;
        fetchCaptcha()
    }
}

/**
 * 注册
 */
const register = async () => {
    // 注册成功之前，先进行校验，校验成功 → 请求，校验失败 → 自动提示
    await registerForm.value.validate()
    await userRegisterService(formModel.value)
    ElMessage.success('注册成功')
    change()
}

/**
 * 登录
 */
const login = async () => {
    try {
        await loginForm.value.validate()
        const res = await userLoginService(formModel.value)
        userStore.setTokens(res.data.accessToken, res.data.refreshToken)
        userStore.setUserId(res.data.userId)
        ElMessage.success('登录成功')
        router.push('/')
    } catch (error) {
        fetchCaptcha() // 登录失败时刷新验证码
    }
}

// 获取验证码
const fetchCaptcha = async () => {
    try {
        const response = await kaptchaService()
        const data = await response.data.data
        captchaUrl.value = 'data:image/png;base64,' + data.value
        formModel.value.kaptchaUuid = data.uuid
    } catch (error) {
        captchaUrl.value = placeholderImage // 设置占位图片
        ElMessage.error('获取验证码失败，请重试')
    }
}

// 页面打开初始化获取一次验证码
fetchCaptcha()

</script>

<template>
    <el-row class="login-page">
        <el-col :span="12" :offset="6" class="login-form">
            <div class="container" ref="container" id="container">
                <div class="form-container sign-up-container">
                    <el-form ref="registerForm" :model="formModel" :rules="rules" v-show="isRegister">
                        <h1>注 册</h1>
                        <div class="social-container">
                            <a href="#" class="social"><i class="fab fa-facebook-f"></i></a>
                            <a href="#" class="social"><i class="fab fa-google-plus-g"></i></a>
                            <a href="#" class="social"><i class="fab fa-linkedin-in"></i></a>
                        </div>
                        <el-form-item prop="username">
                            <el-input type="text" v-model="formModel.username" placeholder="请输入用户名" />
                        </el-form-item>
                        <el-form-item prop="password">
                            <el-input type="password" v-model="formModel.password" placeholder="请输入密码" />
                        </el-form-item>
                        <el-form-item prop="repassword">
                            <el-input type="password" v-model="formModel.repassword" placeholder="请再次输入密码" />
                        </el-form-item>
                        <el-form-item class="form-botton">
                            <el-button @click="register" class="button" type="primary" auto-insert-space>注 册</el-button>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="form-container sign-in-container">
                    <el-form ref="loginForm" :model="formModel" :rules="rules" v-show="!isRegister">
                        <h1>登 录</h1>
                        <div class="social-container">
                            <a href="#" class="social"><i class="fab fa-facebook-f"></i></a>
                            <a href="#" class="social"><i class="fab fa-google-plus-g"></i></a>
                            <a href="#" class="social"><i class="fab fa-linkedin-in"></i></a>
                        </div>

                        <el-form-item prop="username">
                            <el-input type="text" v-model="formModel.username" placeholder="请输入用户名" />
                        </el-form-item>
                        <el-form-item prop="password">
                            <el-input type="password" v-model="formModel.password" placeholder="请输入密码" />
                        </el-form-item>
                        <el-form-item prop="kaptcha">
                            <div style="display: flex; align-items: center;">
                                <el-input type="kaptcha" v-model="formModel.kaptcha" placeholder="请输入验证码">
                                </el-input>
                                <img :src="captchaUrl" style="margin-left: 10px; height: 40px; cursor: pointer;"
                                    @click="fetchCaptcha" />
                            </div>
                        </el-form-item>
                        <a href="#">忘记密码?</a>
                        <el-form-item class="form-botton">
                            <el-button @click="login" class="button" type="primary" auto-insert-space>登 录</el-button>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="overlay-container">
                    <div class="overlay">
                        <div class="overlay-panel overlay-left">
                            <h1>欢迎 回来!</h1>
                            <p>为保持与我们的联系，请使用您的个人信息登录。</p>
                            <button @click="change" class="ghost" id="signIn">登 录</button>
                        </div>
                        <div class="overlay-panel overlay-right">
                            <h1>你好，朋友!</h1>
                            <p>输入您的个人信息，与我们一起开始旅程</p>
                            <button @click="change" class="ghost" id="signUp">注 册</button>
                        </div>
                    </div>
                </div>
            </div>
        </el-col>
    </el-row>
</template>

<style lang="scss" scoped>
h2 {
    text-align: center;
}

p {
    font-size: 14px;
    font-weight: 100;
    line-height: 20px;
    letter-spacing: 0.5px;
    margin: 20px 0 30px;
}

span {
    font-size: 12px;
}

a {
    color: #333;
    font-size: 14px;
    text-decoration: none;
    margin: 15px 0;
}

button {
    border-radius: 20px;
    border: 1px solid #FF4B2B;
    background-color: #FF4B2B;
    color: #FFFFFF;
    font-size: 16px;
    font-weight: bold;
    padding: 12px 45px;
    letter-spacing: 1px;
    text-transform: uppercase;
    transition: transform 80ms ease-in;
}

button:active {
    transform: scale(0.95);
}

button:focus {
    outline: none;
}

button.ghost {
    background-color: transparent;
    border-color: #FFFFFF;
}

form {
    background-color: #FFFFFF;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    padding: 0 50px;
    height: 100%;
    text-align: center;
}

input {
    background-color: #eee;
    border: none;
    padding: 12px 15px;
    margin: 8px 0;
    width: 100%;
}

.login-page {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;

    .el-form-item,
    .el-input,
    .el-input__inner {
        width: 100%;
        height: 40px !important;
        line-height: 40px !important;
    }

    .container {
        background-color: #fff;
        border-radius: 10px;
        box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25),
            0 10px 10px rgba(0, 0, 0, 0.22);
        position: relative;
        overflow: hidden;
        height: 600px;
        max-width: 100%;
        min-height: 480px;
    }

    .form-title,
    .form-botton {
        display: flex;
        flex-direction: column;
        align-items: center;

        h1 {
            font-size: 35px !important;
        }
    }

    .form-container {
        position: absolute;
        top: 0;
        height: 100%;
        transition: all 0.6s ease-in-out;
    }

    .sign-in-container {
        left: 0;
        width: 50%;
        z-index: 2;
    }

    .container.right-panel-active .sign-in-container {
        transform: translateX(100%);
    }

    .sign-up-container {
        left: 0;
        width: 50%;
        opacity: 0;
        z-index: 1;
    }

    .container.right-panel-active .sign-up-container {
        transform: translateX(100%);
        opacity: 1;
        z-index: 5;
        animation: show 0.6s;
    }

    @keyframes show {

        0%,
        49.99% {
            opacity: 0;
            z-index: 1;
        }

        50%,
        100% {
            opacity: 1;
            z-index: 5;
        }
    }

    .overlay-container {
        position: absolute;
        top: 0;
        left: 50%;
        width: 50%;
        height: 100%;
        overflow: hidden;
        transition: transform 0.6s ease-in-out;
        z-index: 100;
    }

    .container.right-panel-active .overlay-container {
        transform: translateX(-100%);
    }

    .overlay {
        background: #FF416C;
        background: -webkit-linear-gradient(to right, #FF4B2B, #FF416C);
        background: linear-gradient(to right, #FF4B2B, #FF416C);
        background-repeat: no-repeat;
        background-size: cover;
        background-position: 0 0;
        color: #FFFFFF;
        position: relative;
        left: -100%;
        height: 100%;
        width: 200%;
        transform: translateX(0);
        transition: transform 0.6s ease-in-out;
    }

    .container.right-panel-active .overlay {
        transform: translateX(50%);
    }

    .overlay-panel {
        position: absolute;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        padding: 0 40px;
        text-align: center;
        top: 0;
        height: 100%;
        width: 50%;
        transform: translateX(0);
        transition: transform 0.6s ease-in-out;
    }

    .overlay-left {
        transform: translateX(-20%);
    }

    .container.right-panel-active .overlay-left {
        transform: translateX(0);
    }

    .overlay-right {
        right: 0;
        transform: translateX(0);
    }

    .container.right-panel-active .overlay-right {
        transform: translateX(20%);
    }

    .social-container {
        margin: 20px 0;
        padding-bottom: 10px;
    }

    .social-container a {
        border: 1px solid #DDDDDD;
        border-radius: 50%;
        display: inline-flex;
        justify-content: center;
        align-items: center;
        margin: 0 5px;
        height: 40px;
        width: 40px;
    }

    footer {
        background-color: #222;
        color: #fff;
        font-size: 14px;
        bottom: 0;
        position: fixed;
        left: 0;
        right: 0;
        text-align: center;
        z-index: 999;
    }

    footer p {
        margin: 10px 0;
    }

    footer i {
        color: red;
    }

    footer a {
        color: #3c97bf;
        text-decoration: none;
    }
}
</style>